package com.lmz.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lmz.cart.feign.ProductFeignService;
import com.lmz.cart.interceptor.cartInterceptor;
import com.lmz.cart.service.cartService;
import com.lmz.cart.vo.Cart;
import com.lmz.cart.vo.CartItem;
import com.lmz.cart.vo.SkuInfoVo;
import com.lmz.cart.vo.UserInfoTo;
import com.lmz.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class cartServiceImpl implements cartService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String cart = (String) cartOps.get(skuId.toString());

        if (StringUtils.isEmpty(cart)) {
            CartItem cartItem = new CartItem();
            //还未添加
            //添加新商品
            CompletableFuture<Void> getSkuInfo = CompletableFuture.runAsync(() -> {
                //远程查询当前要添加的商品信息
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                //添加到购物车
                cartItem.setChecked(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setPrice(skuInfo.getPrice());
                cartItem.setSkuId(skuId);
            }, executor);

            //远程查询sku的组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> SkuAttr = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(SkuAttr);
            }, executor);
            //等待所有任务完成
            CompletableFuture.allOf(getSkuInfo, getSkuSaleAttrValues).get();

            //加入redis
            String jsonCartItem = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), jsonCartItem);
            return cartItem;
        } else {
            //有商品了，修改数量
            CartItem cartItem = JSON.parseObject(cart, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }

    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String s = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(s, CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        //是否登录？
        UserInfoTo userInfoTo = cartInterceptor.threadLocal.get();
        Cart cart = new Cart();
        if (userInfoTo.getUserId() != null) {
            String userKey = CART_PREFIX + userInfoTo.getUserId();
            //判断临时购物车的数据是否进行了合并
            String tempKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempKey);
            if (tempCartItems != null) {
                //临时购物车中有数据,合并购物车
                for (CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                //清空临时购物车
                clearCart(tempKey);
            }
            //获取登录后的购物车
            List<CartItem> cartItems = getCartItems(userKey);
            cart.setItems(cartItems);
        } else {
            String userKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车的购物项
            List<CartItem> cartItems = getCartItems(userKey);
            cart.setItems(cartItems);
        }

        return cart;
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setChecked(check == 1);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), s);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = cartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            List<CartItem> cartItems = getCartItems(CART_PREFIX + userInfoTo.getUserId());
            if (cartItems != null) {
                //获取所有被选中的购物项
                List<CartItem> collect = cartItems.stream().filter(item -> item.getChecked()).map(item -> {
                    //更新为最新价格
                    R r = productFeignService.getPrice(item.getSkuId());
                    String data = (String) r.get("data");
                    BigDecimal price = new BigDecimal(data);
                    item.setPrice(price);
                    return item;
                }).collect(Collectors.toList());
                return collect;
            }
        }
        return null;
    }

    /**
     * 获取购物车中的购物项
     */
    private List<CartItem> getCartItems(String userKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(userKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            List<CartItem> collect = values.stream().map(item -> {
                String str = (String) item;
                return JSON.parseObject(str, CartItem.class);
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }


    /**
     * 获取到要操作的购物车
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = cartInterceptor.threadLocal.get();
        String cartKey;
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }

    /**
     * 清空购物车
     */
    private void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }


}